
package cn.imnu.legalaid.service.impl;

import cn.imnu.legalaid.dto.Consultation.*;
import cn.imnu.legalaid.entity.Consultations;
import cn.imnu.legalaid.entity.ConsultationsMessages;
import cn.imnu.legalaid.mapper.ConsultationsMapper;
import cn.imnu.legalaid.mapper.ConsultationsMessagesMapper;
import cn.imnu.legalaid.service.ConsultationsService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author 18498
 * @description 针对表【consultations(咨询表)】的数据库操作Service实现
 * @createDate 2025-09-19 17:49:09
 */
@Slf4j
@Service
public class ConsultationsServiceImpl extends ServiceImpl<ConsultationsMapper, Consultations>
        implements ConsultationsService {

    @Autowired
    private ConsultationsMapper consultationsMapper;

    @Autowired
    private ConsultationsMessagesMapper messagesMapper;

    @Override
    @Transactional
    public Integer createConsultation(ConsultationDTO consultationDTO) {
        try {
            Consultations consultation = new Consultations();

            // 复制基本属性
            consultation.setClient_id(consultationDTO.getClientId());
            consultation.setLawyer_id(consultationDTO.getLawyerId());
            consultation.setTitle(consultationDTO.getTitle());
            consultation.setCategory(consultationDTO.getCategory());
            consultation.setDescription(consultationDTO.getDescription());
            consultation.setStatus(consultationDTO.getStatus() != null ? consultationDTO.getStatus() : "pending");
            consultation.setScheduled_time(consultationDTO.getScheduledTime());

            // 设置创建和更新时间
            LocalDateTime now = LocalDateTime.now();
            consultation.setCreated_at(now);
            consultation.setUpdated_at(now);

            this.save(consultation);

            log.info("成功创建咨询，ID: {}", consultation.getId());
            return consultation.getId();

        } catch (Exception e) {
            log.error("创建咨询失败", e);
            throw new RuntimeException("创建咨询失败: " + e.getMessage());
        }
    }

    @Override
    public Page<ConsultationDTO> getConsultations(Page<ConsultationDTO> page, ConsultationQueryDTO queryDTO) {
        try {
            return consultationsMapper.selectConsultationsPage(page, queryDTO);
        } catch (Exception e) {
            log.error("查询咨询列表失败", e);
            throw new RuntimeException("查询咨询列表失败: " + e.getMessage());
        }
    }

    @Override
    public ConsultationDTO getConsultationDetail(Integer id) {
        try {
            if (id == null) {
                throw new IllegalArgumentException("咨询ID不能为空");
            }

            ConsultationDTO consultationDTO = consultationsMapper.selectConsultationDetail(id);
            if (consultationDTO == null) {
                log.warn("未找到ID为{}的咨询", id);
            }

            return consultationDTO;

        } catch (Exception e) {
            log.error("查询咨询详情失败，ID: {}", id, e);
            throw new RuntimeException("查询咨询详情失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void updateConsultationStatus(Integer id, String status) {
        try {
            if (id == null || status == null || status.trim().isEmpty()) {
                throw new IllegalArgumentException("咨询ID和状态不能为空");
            }

            UpdateWrapper<Consultations> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id)
                    .set("status", status)
                    .set("updated_at", LocalDateTime.now());

            boolean updated = this.update(updateWrapper);
            if (!updated) {
                throw new RuntimeException("咨询不存在或更新失败");
            }

            log.info("成功更新咨询状态，ID: {}, 新状态: {}", id, status);

        } catch (Exception e) {
            log.error("更新咨询状态失败，ID: {}, 状态: {}", id, status, e);
            throw new RuntimeException("更新咨询状态失败: " + e.getMessage());
        }
    }

    @Override
    public List<MessageDTO> getMessages(Integer consultationId) {
        try {
            if (consultationId == null) {
                throw new IllegalArgumentException("咨询ID不能为空");
            }

            return messagesMapper.selectMessagesByConsultationId(consultationId);

        } catch (Exception e) {
            log.error("查询消息列表失败，咨询ID: {}", consultationId, e);
            throw new RuntimeException("查询消息列表失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Integer sendMessage(MessageDTO messageDTO) {
        try {
            if (messageDTO == null || messageDTO.getConsultationId() == null ||
                    messageDTO.getSenderId() == null) {
                throw new IllegalArgumentException("消息信息不完整");
            }

            ConsultationsMessages message = new ConsultationsMessages();
            message.setConsultation_id(messageDTO.getConsultationId());
            message.setSender_id(messageDTO.getSenderId());
            message.setMessage_type(messageDTO.getMessageType() != null ? messageDTO.getMessageType() : "text");
            message.setContent(messageDTO.getContent());
            message.setFile_url(messageDTO.getFileUrl());
            message.setCreated_at(LocalDateTime.now());
            message.setIs_read(0); // 默认未读

            messagesMapper.insert(message);

            log.info("成功发送消息，ID: {}", message.getId());
            return message.getId();

        } catch (Exception e) {
            log.error("发送消息失败", e);
            throw new RuntimeException("发送消息失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void markMessagesAsRead(Integer consultationId, List<Integer> messageIds) {
        try {
            if (consultationId == null || messageIds == null || messageIds.isEmpty()) {
                throw new IllegalArgumentException("参数不能为空");
            }

            messagesMapper.markMessagesAsRead(consultationId, messageIds);

            log.info("成功标记消息为已读，咨询ID: {}, 消息数量: {}", consultationId, messageIds.size());

        } catch (Exception e) {
            log.error("标记消息为已读失败，咨询ID: {}", consultationId, e);
            throw new RuntimeException("标记消息为已读失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public void submitReview(Integer consultationId, ReviewDTO reviewDTO) {
        try {
            if (consultationId == null || reviewDTO == null) {
                throw new IllegalArgumentException("参数不能为空");
            }

            UpdateWrapper<Consultations> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", consultationId)
                    .set("rating", reviewDTO.getRating())
                    .set("review", reviewDTO.getReview())
                    .set("updated_at", LocalDateTime.now());

            boolean updated = this.update(updateWrapper);
            if (!updated) {
                throw new RuntimeException("咨询不存在或评价提交失败");
            }

            log.info("成功提交咨询评价，ID: {}, 评分: {}", consultationId, reviewDTO.getRating());

        } catch (Exception e) {
            log.error("提交咨询评价失败，咨询ID: {}", consultationId, e);
            throw new RuntimeException("提交咨询评价失败: " + e.getMessage());
        }
    }

    @Override
    public ConsultationDTO acceptConsultation(Integer consultationId, Integer lawyerId) {
        // 查询咨询是否存在且状态为待接单
        Consultations consultation = this.getById(consultationId);
        if (consultation == null) {
            throw new RuntimeException("咨询不存在");
        }

        // 检查咨询状态
        if (!"pending".equals(consultation.getStatus())) {
            throw new RuntimeException("只有待接单的咨询才能被接取");
        }

        // 更新咨询信息
        consultation.setLawyer_id(lawyerId);
        consultation.setStatus("active"); // 设置为进行中状态
        consultation.setUpdated_at(LocalDateTime.now());

        // 保存更新
        boolean updated = this.updateById(consultation);
        if (!updated) {
            throw new RuntimeException("接单失败，请重试");
        }

        // 返回更新后的咨询详情
        return getConsultationDetail(consultationId);
    }
}